<!--
 * @Author: Li Zengkun
 * @Date: 2022-09-28 20:22:55
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-09-29 11:06:50
 * @Description: 
-->
<template>
  <div>
    <el-card>
      <template #header>
        <span>商品分类</span>
      </template>
      <!-- :data="list" -->
      <el-tree
        ref="treeRef"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :default-expanded-keys="[1]"
        lazy
        :load="loadNode"
      >
        <template #default="{ node, data }">
          <span>{{ node.label }}</span>
          <span style="margin-left: 20px"><el-tag>显示顺序： {{data.menu_order}}</el-tag></span>
          <span class="node-action" style="margin-left: 20px">
            <el-button
              type="primary"
              @click.stop="openEditModal(node, data)"
              v-if="node.level > 1"
              size="small"
              >编辑</el-button
            >
            <el-button
              type="success"
              @click.stop="openAddModal(node, data)"
              v-if="node.level < 4"
              size="small"
              >添加</el-button
            >
            <el-button
              type="danger"
              @click.stop="openDeleteModal(node, data)"
              v-if="node.level > 1"
              size="small"
              >删除</el-button
            >
          </span>
        </template>
      </el-tree>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editModalVisible">
      <el-form>
        <el-form-item label="菜单名称（必填）">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="组件名称">
          <el-input
            placeholder="指定此菜单对应的组件名称"
            v-model="editForm.component"
          ></el-input>
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input
            v-model="editForm.path"
            placeholder="指定此菜单的链接地址，选填"
          ></el-input>
        </el-form-item>
        <el-form-item label="显示顺序（必填）">
          <el-input
            v-model="editForm.menu_order"
            placeholder="显示顺序按照数字从小到大，如2001"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editModalVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog title="添加节点" v-model="addModalVisible">
      <el-form>
        <el-form-item label="菜单名称（必填）">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="组件名称">
          <el-input
            placeholder="指定此菜单对应的组件名称"
            v-model="addForm.component"
          ></el-input>
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input
            v-model="addForm.path"
            placeholder="指定此菜单的链接地址，选填"
          ></el-input>
        </el-form-item>
        <el-form-item label="显示顺序（必填）">
          <el-input
            v-model="addForm.menu_order"
            placeholder="显示顺序按照数字从小到大，如2001"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addModalVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, reactive } from "vue";
import { menu } from "@/api";
import ImgUpload from "@/components/common/ImgUpload.vue";

const list = (await menu.getAll({ type: "tree" })).data;
const defaultProps = { label: "name" };
const treeRef = ref(null);
console.log(list);

// 懒加载节点
const loadNode = async (node, resolve) => {
  // 根节点 level=0
  if (node.level === 0) {
    let { data } = await menu.getChild({ pId: 0 });
    return resolve(data);
  } else {
    let { data } = await menu.getChild({ pId: node.data.id });
    resolve(data);
  }
};

// dialog 对话框
const editModalVisible = ref(false);
const addModalVisible = ref(false);

// 编辑
const editForm = ref({});
const openEditModal = (node, data) => {
  editForm.value = node.data;
  editModalVisible.value = true;
};
const handleEdit = async () => {
  if (editForm.value.name == "" || editForm.value.menu_order == "") {
    ElMessage.error("请填写名称和显示顺序");
    return;
  }
  let { status, msg, data } = await menu.update(
    editForm.value.id,
    editForm.value
  );
  ElMessage({
    type: status ? "success" : "error",
    message: msg,
  });
  editForm.value = {};
  editModalVisible.value = false;
};

// 添加
let currentNode = {};
let currentLevel = 0;
const addForm = ref({
  name: "",
  component: null,
  path: "",
  menu_order: "",
});
const openAddModal = (node, data) => {
  addForm.value.pId = node.data.id;
  addForm.value.level = node.data.level;
  addModalVisible.value = true;
  //   转存data
  currentNode = node;
  currentLevel = node.level;
  // 储存操作层级
};
const handleAdd = async () => {
  if (addForm.value.name == ""|| addForm.value.menu_order == "") {
    ElMessage.error("请填写名称和显示顺序");
    return;
  }
  let { status, msg, data } = await menu.add(addForm.value);
  if (status) {
    treeRef.value.append({ ...addForm.value, ...data }, currentNode);
    currentNode = {};
  }
  ElMessage({
    type: status ? "success" : "error",
    message: msg,
  });
  addForm.value = {
    name: "",
    component: null,
    path: "",
    menu_order: "",
  };
  addModalVisible.value = false;
};

// 删除
const openDeleteModal = (node, data) => {
  ElMessageBox.confirm(
    `此操作将永久删除 ${data.name} 分类, 是否继续?`,
    "Warning",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      let { status, msg } = await menu.remove(data.id);
      if (status) {
        node.remove();
      }
      ElMessage({
        type: status ? "success" : "error",
        message: msg,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
</script>

<style lang='less' scoped>
</style>

